package com.changgou.item.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.goods.feign.CategoryFeign;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.feign.SpuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.goods.pojo.Spu;
import com.changgou.item.service.PageService;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：hushengjin
 */

@Service
public class PageServiceImpl implements PageService {

    @Autowired
    private CategoryFeign categoryFeign;
    @Autowired
    private SpuFeign spuFeign;
    @Autowired
    private SkuFeign skuFeign;
    @Autowired
    private TemplateEngine templateEngine;
    @Value("${pagepath}")
    private String pagepath;

    /**
     * 根据商品的ID 生成静态页
     *
     * @param spuId
     */
    @Override
    public void createPageHtml(Long spuId) {
        //1.上下文
        Context context = new Context();
        Map<String, Object> dataModel = buildDataModel(spuId);
        context.setVariables(dataModel);
        //2.准备文件
        File dir = new File(pagepath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File dest = new File(dir, spuId + ".html");
        //3.生成静态页面
        PrintWriter writer = null;
        try {
            writer = new PrintWriter(dest, "UTF-8");
            templateEngine.process("item", context, writer);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    /**
     * 根据商品ID 删除静态页
     *
     * @param spuId
     */
    @Override
    public void deletePageHtml(Long spuId) {

        File dir = new File(pagepath);
        File dest = new File(dir, spuId + ".html");
        if (dest.exists()) {
            dest.delete();
        }
    }

    /**
     * 构建数据模型
     *
     * @param spuId
     * @return
     */
    private Map<String, Object> buildDataModel(Long spuId) {
        //构建数据模型
        Map<String, Object> dataMap = new HashMap<String, Object>();
        //获取Spu
        Result<Spu> spuResult = spuFeign.findById(spuId);
        Spu spu = spuResult.getData();
        dataMap.put("spu", spu);
        //获取分类信息
        dataMap.put("category1", categoryFeign.findById(spu.getCategory1Id()).getData());
        dataMap.put("category2", categoryFeign.findById(spu.getCategory2Id()).getData());
        dataMap.put("category3", categoryFeign.findById(spu.getCategory3Id()).getData());
        //获取图片数据
        if (spu.getImages() != null) {
            dataMap.put("imageList", spu.getImages().split(","));
        }
        //可选规格数据spec_items
        dataMap.put("specificationList", JSON.parseObject(spu.getSpecItems(), Map.class));

        //根据spuid查询sku集合
        Sku skuCondition = new Sku();
        skuCondition.setSpuId(spu.getId());
        Result<List<Sku>> skuResultList = skuFeign.findList(skuCondition);
        dataMap.put("skuList", skuResultList.getData());
        return dataMap;
    }
}
